//
//  YFree.swift
//  Runner
//
//  Created by YMac on 2019/4/11.
//  Copyright © 2019 The Chromium Authors. All rights reserved.
//

import Flutter
import UIKit

class YFlutterAppDelegate:FlutterAppDelegate {
    override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        onYConfig()
        onYCreated(application, didFinishLaunchingWithOptions: launchOptions)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    func onYCreated(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {}
    
    func onYConfig() {}
}

open class YFlutterPlugin {
     public static func register(with appDelegate:UIApplicationDelegate) {
        let navigationController = UINavigationController(rootViewController: appDelegate.window!!.rootViewController!)
        navigationController.isNavigationBarHidden = true
        appDelegate.window!!.rootViewController = navigationController
        FlutterMethodChannel(name: "YFreePlugin", binaryMessenger: navigationController.viewControllers.first as! FlutterBinaryMessenger).setMethodCallHandler { methodCall, result in
            let arguments = methodCall.arguments as? NSDictionary
            switch methodCall.method {
            default: result(FlutterMethodNotImplemented)
            }
        }
    }
    
    public static func yRunFlutter(className: String, methodName: String, params: [String: Any]? = nil, callBack: ((Any) -> ())? = nil) {
        let appDelegate = UIApplication.shared.delegate as! UIApplicationDelegate
        let navigationController = UINavigationController(rootViewController: appDelegate.window!!.rootViewController!)
        FlutterMethodChannel(name: className, binaryMessenger: (navigationController.viewControllers.first) as! FlutterBinaryMessenger).invokeMethod(methodName, arguments: params) { (result) in
            if result != nil { callBack?(result!) }
        }
    }
}
